#encoding: utf-8

=begin
    VIP渠道4%图贝奖励程序
    功能：为指定VIP渠道用户发放上个月订单实际支付金额4%的图贝奖励
    
    使用方法：
    ruby vip-channel-reward.rb [月份] [是否执行]
    
    参数说明：
    - 月份：格式为YYYY-MM，如2024-01，默认为上个月
    - 是否执行：true/false，默认为false（仅预览，不实际执行）
    
    示例：
    ruby vip-channel-reward.rb 2024-01 false  # 预览2024年1月的奖励
    ruby vip-channel-reward.rb 2024-01 true   # 实际执行2024年1月的奖励
=end

require 'mysql2'
require 'time'
require 'date'

# 加载数据库连接和工具函数
load 'rds_api.rb'
@rds = @rds_tt

# VIP渠道用户ID列表（静态配置）
VIP_CHANNEL_UIDS = [
    # 在这里添加VIP渠道用户的UID
    # 示例：1001, 1002, 1003
    1782, 15417, 29445, 20187, 6576, 6322, 23614, 25694, 9663, 2302, 32, 14104, 5301, 5401, 1533, 19232, 19233, 20079, 27807, 30156
]

# 奖励比例：4%
REWARD_RATE = 0.04

#根据年月字符串获取该月的开始和结束时间戳 参数：year_month - 格式为"YYYY-MM" 返回：[start_time, end_time] - Unix时间戳数组
def get_month_start_end_time(year_month)
    begin
        year, month = year_month.split('-').map(&:to_i)
        start_date = Date.new(year, month, 1)
        end_date = start_date.next_month - 1
        
        start_time = Time.parse("#{start_date} 00:00:00").to_i
        end_time = Time.parse("#{end_date} 23:59:59").to_i
        
        return [start_time, end_time]
    rescue => e
        puts "错误：无效的月份格式 #{year_month}，请使用YYYY-MM格式"
        exit 1
    end
end

#获取指定VIP渠道用户在上个月的订单实际支付金额 参数： - uid: 用户ID - start_time: 开始时间戳 - end_time: 结束时间戳 返回：实际支付金额（元）
def get_vip_channel_sales(uid, start_time, end_time)
    sql = "SELECT SUM(pay_price - refund_price) as total_paid 
           FROM tutem_mall.eb_store_order 
           WHERE paid = 1 
           AND pay_time >= #{start_time} 
           AND pay_time <= #{end_time} 
           AND uid IN (
               SELECT uid FROM tutem_mall.eb_user WHERE spread_uid = #{uid}
           )"
    
    result = queryRds(sql)
    total_paid = 0.0
    
    result.each do |row|
        total_paid = row['total_paid'].to_f if row['total_paid']
    end
    
    return total_paid
end

#获取用户基本信息 参数：uid - 用户ID 返回：用户信息哈希
def get_user_info(uid)
    sql = "SELECT uid, real_name, nickname, phone, now_money 
           FROM tutem_mall.eb_user 
           WHERE uid = #{uid}"
    
    result = queryRds(sql)
    user_info = {}
    
    result.each do |row|
        user_info = {
            'uid' => row['uid'],
            'real_name' => row['real_name'] || '',
            'nickname' => row['nickname'] || '',
            'phone' => row['phone'] || '',
            'now_money' => row['now_money'].to_f
        }
    end
    
    return user_info
end

#检查用户是否已经获得过该月的奖励 参数： - uid: 用户ID - year_month: 年月字符串 返回：true表示已奖励，false表示未奖励
def check_already_rewarded(uid, year_month)
    link_id = "VIP-REWARD-#{year_month}"
    sql = "SELECT COUNT(*) as count 
           FROM tutem_mall.eb_user_bill 
           WHERE uid = #{uid} 
           AND link_id = '#{link_id}'"
    
    result = queryRds(sql)
    count = 0
    
    result.each do |row|
        count = row['count'].to_i
    end
    
    return count > 0
end

#计算奖励金额 参数：total_paid - 实际支付金额 返回：奖励金额（图贝）
def calculate_reward(total_paid)
    return (total_paid * REWARD_RATE).round(2)
end

#为用户发放图贝奖励 参数： - uid: 用户ID - reward_amount: 奖励金额 - year_month: 年月 - total_paid: 实际支付金额 返回：是否成功
def award_tupay_to_user(uid, reward_amount, year_month, total_paid)
    # 获取用户当前图贝余额
    user_info = get_user_info(uid)
    current_balance = user_info['now_money']
    new_balance = (current_balance + reward_amount).round(2)
    
    # 生成奖励记录的唯一标识
    link_id = "VIP-REWARD-#{year_month}"
    title = "VIP渠道奖励#{year_month}"
    mark = "#{year_month}期间渠道销售#{total_paid.round(2)}元，按4%比例奖励#{reward_amount}图贝"
    add_time = Time.now.to_i
    
    # 准备SQL语句
    sqls = []
    
    # 更新用户图贝余额
    sqls << "UPDATE tutem_mall.eb_user SET now_money = #{new_balance} WHERE uid = #{uid}"
    
    # 插入奖励记录
    sqls << "INSERT INTO tutem_mall.eb_user_bill 
             (uid, link_id, pm, title, category, type, number, balance, mark, add_time, status, take) 
             VALUES (#{uid}, '#{link_id}', 1, '#{title}', 'now_money', 'brokerage', #{reward_amount}, #{new_balance}, '#{mark}', #{add_time}, 1, 0)"
    
    # 执行事务
    success = commitTrans(sqls)
    
    if success
        puts "✓ 用户##{uid} #{user_info['real_name']} 奖励发放成功：#{reward_amount}图贝"
        puts "  渠道销售：#{total_paid.round(2)}元，当前余额：#{new_balance}图贝"
    else
        puts "✗ 用户##{uid} #{user_info['real_name']} 奖励发放失败"
    end
    
    return success
end

#预览奖励情况（不实际执行）
def preview_rewards(year_month, start_time, end_time)
    puts "=" * 60
    puts "VIP渠道4%图贝奖励预览 - #{year_month}"
    puts "=" * 60
    puts "统计期间：#{Time.at(start_time).strftime('%Y-%m-%d')} 至 #{Time.at(end_time).strftime('%Y-%m-%d')}"
    puts "奖励比例：#{REWARD_RATE * 100}%"
    puts
    
    total_sales = 0.0
    total_rewards = 0.0
    valid_users = 0
    
    VIP_CHANNEL_UIDS.each do |uid|
        user_info = get_user_info(uid)
        next if user_info.empty?
        
        # 检查是否已奖励
        already_rewarded = check_already_rewarded(uid, year_month)
        
        # 获取渠道销售金额
        sales_amount = get_vip_channel_sales(uid, start_time, end_time)
        
        if sales_amount > 0
            reward_amount = calculate_reward(sales_amount)
            total_sales += sales_amount
            total_rewards += reward_amount
            valid_users += 1
            
            status = already_rewarded ? "已奖励" : "待奖励"
            puts "用户##{uid} #{user_info['real_name']} (#{user_info['phone']})"
            puts "  渠道销售：#{sales_amount.round(2)}元"
            puts "  应奖励：#{reward_amount}图贝"
            puts "  状态：#{status}"
            puts "  当前余额：#{user_info['now_money']}图贝"
            puts
        else
            puts "用户##{uid} #{user_info['real_name']} - 无销售记录"
        end
    end
    
    puts "=" * 60
    puts "汇总统计："
    puts "有效用户数：#{valid_users}"
    puts "总销售金额：#{total_sales.round(2)}元"
    puts "总奖励金额：#{total_rewards.round(2)}图贝"
    puts "=" * 60
end

#执行奖励发放
def execute_rewards(year_month, start_time, end_time)
    puts "=" * 60
    puts "开始执行VIP渠道4%图贝奖励 - #{year_month}"
    puts "=" * 60
    
    success_count = 0
    total_sales = 0.0
    total_rewards = 0.0
    
    VIP_CHANNEL_UIDS.each do |uid|
        user_info = get_user_info(uid)
        next if user_info.empty?
        
        # 检查是否已奖励
        if check_already_rewarded(uid, year_month)
            puts "⚠ 用户##{uid} #{user_info['real_name']} 已获得过#{year_month}的奖励，跳过"
            next
        end
        
        # 获取渠道销售金额
        sales_amount = get_vip_channel_sales(uid, start_time, end_time)
        
        if sales_amount > 0
            reward_amount = calculate_reward(sales_amount)
            
            # 发放奖励
            if award_tupay_to_user(uid, reward_amount, year_month, sales_amount)
                success_count += 1
                total_sales += sales_amount
                total_rewards += reward_amount
            end
        else
            puts "⚠ 用户##{uid} #{user_info['real_name']} 无销售记录，跳过奖励"
        end
        
        puts
    end
    
    puts "=" * 60
    puts "奖励发放完成："
    puts "成功发放：#{success_count}人"
    puts "总销售金额：#{total_sales.round(2)}元"
    puts "总奖励金额：#{total_rewards.round(2)}图贝"
    puts "=" * 60
end

def main
    # 解析命令行参数
    year_month = ARGV[0] || (Date.today << 1).strftime('%Y-%m')  # 默认上个月
    execute = ARGV[1] == 'true'  # 默认仅预览
    
    # 验证VIP渠道用户列表
    if VIP_CHANNEL_UIDS.empty?
        puts "错误：VIP_CHANNEL_UIDS列表为空，请在程序中配置VIP渠道用户ID"
        exit 1
    end
    
    # 获取时间范围
    start_time, end_time = get_month_start_end_time(year_month)
    
    puts "VIP渠道4%图贝奖励程序"
    puts "目标月份：#{year_month}"
    puts "执行模式：#{execute ? '实际执行' : '预览模式'}"
    puts
    
    if execute
        # 确认执行
        puts "警告：即将执行实际的奖励发放操作！"
        print "确认继续？(y/N): "
        confirmation = STDIN.gets.chomp.downcase
        
        if confirmation == 'y' || confirmation == 'yes'
            execute_rewards(year_month, start_time, end_time)
        else
            puts "操作已取消"
        end
    else
        preview_rewards(year_month, start_time, end_time)
    end
end

# 程序入口
if __FILE__ == $0
    main
end
